package com.itrident.action;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.ToggleAction;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiJavaFile;
import com.intellij.psi.impl.source.PsiClassImpl;
import com.intellij.psi.impl.source.PsiJavaFileImpl;
import com.itrident.store.EnumsManagerPersistentState;
import org.jetbrains.annotations.NotNull;

public class RecordEnumsAction extends ToggleAction {

    private String className;

    @Override
    public void update(@NotNull AnActionEvent e) {
        PsiFile psiFile = e.getRequiredData (CommonDataKeys.PSI_FILE);
        if(psiFile instanceof PsiJavaFileImpl){
            PsiClassImpl psiClass = ((PsiJavaFileImpl) psiFile).findChildByClass (PsiClassImpl.class);
            if(!psiClass.isEnum ()){
                e.getPresentation ().setVisible (false);
            }
            super.update (e);
        }else{
            e.getPresentation ().setVisible (false);
        }
    }

    @Override
    public boolean isSelected(AnActionEvent e) {
        Project project = e.getRequiredData (CommonDataKeys.PROJECT);
        PsiFile psiFile = e.getRequiredData (CommonDataKeys.PSI_FILE);
        if(psiFile instanceof PsiJavaFile){
            String packageName = ((PsiJavaFile) psiFile).getPackageName ();
            String name = psiFile.getName ();
            String path = packageName +"."+ name;
            className = path.substring (0,path.length () - 5);
            EnumsManagerPersistentState enumsManagerPersistentState = EnumsManagerPersistentState.getInstance (project);
            return enumsManagerPersistentState.isExist(className);
        }

        return false;
    }

    @Override
    public void setSelected(AnActionEvent e, boolean state) {
        Project project = e.getRequiredData (CommonDataKeys.PROJECT);
        EnumsManagerPersistentState enumsManagerPersistentState = EnumsManagerPersistentState.getInstance (project);
        if(state){
            PsiFile psiFile = e.getRequiredData (CommonDataKeys.PSI_FILE);
            enumsManagerPersistentState.addEnumsWrapper (psiFile, this.className);
        }else{
            enumsManagerPersistentState.delEnumsWrapper (this.className);
        }
    }



}
